package com.bolt.common.utils;

import java.time.temporal.ChronoUnit;

/**
 * Created by Administrator on 2020/10/20.
 */
public enum DateUnit {
    /**
     * 一毫秒
     */
    MS(1, "毫秒"),
    /**
     * 一秒的毫秒数
     */
    SECOND(1000, "秒"),
    /**
     * 一分钟的毫秒数
     */
    MINUTE(SECOND.getMillis() * 60, "分钟"),
    /**
     * 一小时的毫秒数
     */
    HOUR(MINUTE.getMillis() * 60, "小时"),
    /**
     * 一天的毫秒数
     */
    DAY(HOUR.getMillis() * 24, "天"),
    /**
     * 一周的毫秒数
     */
    WEEK(DAY.getMillis() * 7, "周");

    private final long millis;

    private final String name;

    DateUnit(long millis, String name) {
        this.millis = millis;
        this.name = name;
    }

    /**
     * @return 单位对应的毫秒数
     */
    public long getMillis() {
        return this.millis;
    }

    /**
     * 获取单位名称
     */
    public String getName() {
        return this.name;
    }

    /**
     * 单位兼容转换，将DateUnit转换为对应的{@link ChronoUnit}
     */
    public ChronoUnit toChronoUnit() {
        return DateUnit.toChronoUnit(this);
    }

    /**
     * 单位兼容转换，将{@link ChronoUnit}转换为对应的DateUnit
     */
    public static DateUnit of(ChronoUnit unit) {
        switch (unit) {
            case MICROS:
                return DateUnit.MS;
            case SECONDS:
                return DateUnit.SECOND;
            case MINUTES:
                return DateUnit.MINUTE;
            case HOURS:
                return DateUnit.HOUR;
            case DAYS:
                return DateUnit.DAY;
            case WEEKS:
                return DateUnit.WEEK;
        }
        return null;
    }

    /**
     * 单位兼容转换，将DateUnit转换为对应的{@link ChronoUnit}
     */
    public static ChronoUnit toChronoUnit(DateUnit unit) {
        switch (unit) {
            case MS:
                return ChronoUnit.MICROS;
            case SECOND:
                return ChronoUnit.SECONDS;
            case MINUTE:
                return ChronoUnit.MINUTES;
            case HOUR:
                return ChronoUnit.HOURS;
            case DAY:
                return ChronoUnit.DAYS;
            case WEEK:
                return ChronoUnit.WEEKS;
        }
        return null;
    }
}
